package com.wg.dome.chat;

import com.wg.common.annotation.Service;
import com.wg.common.net.OperationRequest;
import com.wg.common.thread.fiber.IFiber;
import com.wg.common.thread.fiber.PoolFiber;
import com.wg.dome.ClientPeer;
import com.wg.dome.operation.ChatRequest;
import com.wg.common.net.SendParameters;

import java.util.HashMap;

@Service
public class ChatLobby {
    private final IFiber fiber = new PoolFiber();
    private final HashMap<String, ChatChannel> chatChannels = new HashMap<>(200);

    public ChatLobby() {
        fiber.start();
    }

    public void onAddChannel(String channel, ClientPeer clientPeer) {
        this.fiber.enqueue(() -> handleAddChatChannel(channel, clientPeer));
    }

    public void onRemoveChannel(String channel, ClientPeer clientPeer) {
        this.fiber.enqueue(() -> handleRemoveChannel(channel, clientPeer));
    }

    public void onRemoveAllChannel(ClientPeer clientPeer) {
        this.fiber.enqueue(() -> handleRemoveAllChannel(clientPeer));
    }

    public void onSendChat(OperationRequest request, SendParameters sendParameters) {
        this.fiber.enqueue(() -> handleSendChat(request, sendParameters));
    }

    private void handleAddChatChannel(String channel, ClientPeer clientPeer) {
        ChatChannel chatChannel = chatChannels.computeIfAbsent(channel, ChatChannel::new);
        chatChannel.addPeer(clientPeer);
    }

    private void handleRemoveChannel(String channel, ClientPeer clientPeer) {
        ChatChannel chatChannel = chatChannels.get(channel);
        if (chatChannel == null){
            return;
        }
        chatChannel.removePeer(clientPeer);
    }

    private void handleRemoveAllChannel(ClientPeer clientPeer) {
        chatChannels.forEach((key, value)->{
            value.removePeer(clientPeer);
        });
    }

    private void handleSendChat(OperationRequest request, SendParameters sendParameters) {
        ChatRequest chatRequest = new ChatRequest(request);
        ChatChannel chatChannel = chatChannels.get(chatRequest.getChatName());
        if (chatChannel == null){
            return;
        }
        chatChannel.sendChat(chatRequest, sendParameters);
    }

}
